package com.qingxin.sys.verifier;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.qingxin.sys.verifier.rules.RequestRule;

/**
 * Request系统参数验证
 * <br>
 * @author JiWangli
 */
public class Request extends VerifyItem {
	
	private String name;
	private String compare;	//验证方式：and所有规则全部通过、or只要有一条规则通过即可

	
	public Request() {
		this.name = "";
		this.compare = "and";
	}
	
	
	@Override
	public boolean verify(FormMsg formMsg, FormMap formMap) {
		if(rules.size() == 0){
			return true;
		}
		boolean all = "and".equalsIgnoreCase(compare);
		boolean pass = false;
		VerifyMsg nopassVerifyMsg = null;
		for(VerifyRule rule : rules) {
			if(!rule.isBackground()){
				continue;
			}
			VerifyMsg verifyMsg = rule.isValid(null, null, null, formMap);
			if(verifyMsg != null){
				if(nopassVerifyMsg==null){
					nopassVerifyMsg = verifyMsg;
				}
			}
			if(!all && verifyMsg==null){
				pass = true;
				break;
			}
			if(all && verifyMsg != null){
				break;
			}
		}
		if(nopassVerifyMsg == null){
			pass = true;
		}
		if(!pass && nopassVerifyMsg != null){
			formMsg.addMessage(nopassVerifyMsg);
		}
		return pass;
	}
	
	
	@Override
	public Map<String, Object> getItemCfg() {
		return null;//不支持前台验证
	}
	
	
	@Override
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getCompare() {
		return compare;
	}
	public void setCompare(String compare) {
		this.compare = compare;
	}


	public void parseRules(String rulesExpr, boolean single) {
		String[] exprArray = null;
		if(single){
			exprArray = new String[]{rulesExpr};
		}else{
			exprArray = rulesExpr.trim().split("\\s+");
		}
		for(String expr : exprArray) {
			Matcher m = null;
			if((m = Pattern.compile("(\\w+)(:(\\w+)?)?\\[(.+?)(,(.+))?\\](\\{(.+)\\})?", Pattern.CASE_INSENSITIVE).matcher(expr)) != null && m.find()){
				RequestRule rule = new RequestRule();
				rule.setRuleArgs(m.group(3));
				rule.setScope(m.group(1));
				rule.setName(m.group(4));
				rule.setValue(m.group(6));
				String error = m.group(8);
				if(error == null){
					error = rule.getScope()+"["+rule.getName()+"]值无效.";
				}
				rule.setError(error);
				addRule(rule);
			}
			
		}//for
	}
	
	
}
